package com.smart.vista.panel;

import com.smart.comp.TablaPadre;
import com.smart.entity.Articulos;
import com.smart.entity.Grupos;
import com.smart.main.Main;
import com.smart.main.Principal;
import com.smart.main.Transaccion;
import com.smart.vista.dialog.ArticulosNuevo;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;

public class ArticulosVista extends javax.swing.JPanel {

    private static DefaultTableModel modeloTblArticulos;
    private TableColumnModel modeloColumna;
    private ArticulosNuevo jdNuevo;
    private TableRowSorter filtro;

    public ArticulosVista() {
        initComponents();
        modeloTblArticulos = (DefaultTableModel) tblArticulos.getModel();
        filtro = (TableRowSorter) tblArticulos.getRowSorter();
        modeloColumna = tblArticulos.getColumnModel();
        cargarTabla();
        anchoColumna();
    }

    public static DefaultTableModel getModeloTblArticulos() {
        return modeloTblArticulos;
    }

    public void cargarTabla() {
        String HQL = "select a.idarticulo, a.codigoarticulo, a.descripcion, a.costo, a.grupos from Articulos a";
        List<Object[]> lstArticulos = Transaccion.executeHQLQuery(HQL);
        for (int i = 0; i < lstArticulos.size(); i++) {
            Integer id = Integer.parseInt(lstArticulos.get(i)[0].toString());
            String codigoArticulo = lstArticulos.get(i)[1].toString();
            String descripcion = lstArticulos.get(i)[2].toString();
            Double costo = Double.parseDouble(lstArticulos.get(i)[3].toString());
            Locale.setDefault(Locale.ENGLISH);
            DecimalFormat costoFormato = new DecimalFormat("0.00");
            Grupos objGrupo = (Grupos) lstArticulos.get(i)[4];
            String grupo = objGrupo.getDescripcion();
            Object object[] = {id, codigoArticulo, descripcion, costoFormato.format(costo), grupo, "0"};
            getModeloTblArticulos().addRow(object);
        }
    }

    private void anchoColumna() {
        setArchoColumna(0, 0);
        setArchoColumna(1, 180);
        setArchoColumna(3, 90);
        setArchoColumna(4, 200);
        setArchoColumna(5, 80);
    }

    private void setArchoColumna(int columna, int ancho) {
        TableColumn columnaTabla = modeloColumna.getColumn(columna);
        columnaTabla.setPreferredWidth(ancho);
        columnaTabla.setMinWidth(ancho);
        columnaTabla.setMaxWidth(ancho);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        scpGuiasSoporte = new javax.swing.JScrollPane();
        tblArticulos = new TablaPadre();
        pnlBotones = new javax.swing.JPanel();
        btnEditar = new javax.swing.JButton();
        btnNuevo = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnBuscar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();

        tblArticulos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "Codigo", "Descripcion", "Costo", "Grupo", "Stock"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblArticulos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblArticulosMouseClicked(evt);
            }
        });
        scpGuiasSoporte.setViewportView(tblArticulos);

        pnlBotones.setLayout(new java.awt.GridBagLayout());

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/smart/recursos/editar2.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.setToolTipText("Editar Guia");
        btnEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 37;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pnlBotones.add(btnEditar, gridBagConstraints);

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/smart/recursos/nuevo.png"))); // NOI18N
        btnNuevo.setText("Nuevo");
        btnNuevo.setToolTipText("Nueva Guia");
        btnNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 37;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pnlBotones.add(btnNuevo, gridBagConstraints);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/smart/recursos/eliminar.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.setToolTipText("Eliminar Guia");
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 37;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        pnlBotones.add(btnEliminar, gridBagConstraints);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/smart/recursos/buscar.png"))); // NOI18N
        btnBuscar.setText("Buscar");
        btnBuscar.setToolTipText("Buscar Guia");
        btnBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 37;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        pnlBotones.add(btnBuscar, gridBagConstraints);

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/smart/recursos/salir.png"))); // NOI18N
        btnSalir.setText("Salir");
        btnSalir.setToolTipText("Salir");
        btnSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 37;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        pnlBotones.add(btnSalir, gridBagConstraints);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlBotones, javax.swing.GroupLayout.DEFAULT_SIZE, 947, Short.MAX_VALUE)
            .addComponent(scpGuiasSoporte, javax.swing.GroupLayout.DEFAULT_SIZE, 947, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(scpGuiasSoporte, javax.swing.GroupLayout.DEFAULT_SIZE, 467, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        Principal.tabContenedor.remove(0);
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        jdNuevo = new ArticulosNuevo(Main.PADRE, true);
        jdNuevo.setVisible(true);
        jdNuevo.dispose();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        if (tblArticulos.getSelectedRowCount() >= 1) {
            int id = Integer.parseInt(tblArticulos.getValueAt(tblArticulos.getSelectedRow(), 0).toString());
            String descripcion = tblArticulos.getValueAt(tblArticulos.getSelectedRow(), 2).toString();
            int rpta = JOptionPane.showConfirmDialog(this, "Seguro de querer eliminar el articulo: " + descripcion, "Articulos", JOptionPane.YES_NO_OPTION);
            if (rpta == JOptionPane.YES_OPTION) {
                String HQL = "delete from Articulos a where a.idarticulo = " + id;
                Integer resultado = Transaccion.executeHQLUpdate(HQL);
                if (resultado > 0) {
                    modeloTblArticulos.removeRow(tblArticulos.getSelectedRow());
                } else {
                    JOptionPane.showMessageDialog(this, "No ha podifo eliminar el registro");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "No ha seleccionado un registro para eliminar");
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        if (tblArticulos.getSelectedRowCount() >= 1) {
            int id = Integer.parseInt(tblArticulos.getValueAt(tblArticulos.getSelectedRow(), 0).toString());
            String HQL = "select a.idarticulo, a.codigoarticulo, a.descripcion, a.costo, a.grupos from Articulos a where a.idarticulo=" + id;
            List<Object[]> lstArticulos = Transaccion.executeHQLQuery(HQL);
            for (int i = 0; i < lstArticulos.size(); i++) {
                Articulos objArticuloParaActualizar = new Articulos();
                System.out.println(lstArticulos.get(i)[0].toString());
                objArticuloParaActualizar.setIdarticulo(Integer.parseInt(lstArticulos.get(i)[0].toString()));
                objArticuloParaActualizar.setCodigoarticulo(lstArticulos.get(i)[1].toString());
                objArticuloParaActualizar.setDescripcion(lstArticulos.get(i)[2].toString());
                objArticuloParaActualizar.setCosto(Double.parseDouble(lstArticulos.get(i)[3].toString()));
                objArticuloParaActualizar.setGrupos((Grupos) lstArticulos.get(i)[4]);
                jdNuevo = new ArticulosNuevo(Main.PADRE, true);
                jdNuevo.setObjArticuloParaActualizar(objArticuloParaActualizar);
                jdNuevo.setVisible(true);
                jdNuevo.dispose();
                modeloTblArticulos.setValueAt(objArticuloParaActualizar.getCodigoarticulo(), tblArticulos.getSelectedRow(), 1);
                modeloTblArticulos.setValueAt(objArticuloParaActualizar.getDescripcion(), tblArticulos.getSelectedRow(), 2);
                modeloTblArticulos.setValueAt(objArticuloParaActualizar.getCosto(), tblArticulos.getSelectedRow(), 3);
                modeloTblArticulos.setValueAt(objArticuloParaActualizar.getGrupos().getDescripcion(), tblArticulos.getSelectedRow(), 4);
                jdNuevo = null;
            }
        } else {
            JOptionPane.showMessageDialog(this, "No ha seleccionado un registro para editar");
        }
    }//GEN-LAST:event_btnEditarActionPerformed

    private void tblArticulosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblArticulosMouseClicked
        if (evt.getClickCount() == 2) {
            btnEditarActionPerformed(null);
        }
    }//GEN-LAST:event_tblArticulosMouseClicked

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        String buscar = JOptionPane.showInputDialog(this, "Ingrese Busqueda");
        filtrar(buscar);
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void filtrar(String buscar) {
        filtro.setRowFilter(RowFilter.regexFilter("(?i)^"+buscar));
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JButton btnSalir;
    private javax.swing.JPanel pnlBotones;
    private javax.swing.JScrollPane scpGuiasSoporte;
    private javax.swing.JTable tblArticulos;
    // End of variables declaration//GEN-END:variables
}
